package com.mybatisx.mybatisplus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatisx.mybatisplus.aop.TokenService;
import com.mybatisx.mybatisplus.aop.UserLoginToken;
import com.mybatisx.mybatisplus.entity.User;
import com.mybatisx.mybatisplus.service.UserService;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author wuyue
 * @date 2020/11/30 17:35
 */

@RestController
@CrossOrigin
@RequestMapping("/user")
@Log4j2
public class LoginController {
    @Autowired
   private UserService userService;
    @Autowired
    private TokenService tokenService;

    //登录
    @PostMapping("/login")
    @ResponseBody
    public Object login(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
         QueryWrapper queryWrapper=new QueryWrapper<>();
         queryWrapper.eq("code",user.getCode());
        User userForBase = userService.getOne(queryWrapper);
        if (userForBase == null) {
            jsonObject.put("message", "登录失败,用户不存在");
            return jsonObject;
        } else {
            if (!userForBase.getCode().equals(user.getCode())) {
                jsonObject.put("message", "登录失败,密码错误");
                return jsonObject;
            } else {
                String token = tokenService.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage() {
        try {
            return "你已通过验证";
        } catch (Exception e) {
            log.error("异常信息[]",e);
            return null;
        }

    }
}
